import React, { useEffect, useRef, useState } from 'react';
import { connect } from 'react-redux';
import { ctrlSong } from '../../../store/actions/music.action';
import { once } from '../../../utils/common';
import { configPlayBtn, hasEnded } from '../../../utils/progressbar';
import ProgressBar from '../ProgressBar';
import './index.css';

const mapStateToProps = state => {
    return {
        music: state.music
    }
}
const mapDispatchToProps = dispatch => {
    return {
        ctrlSong: (...args) => dispatch(ctrlSong(...args))
    }
}

let curMusicTime = {
    value: ''
};

const configPlayBtnOnce = once(configPlayBtn),
    playBtnClassNames = {
        prefix: 'iconfont icon-play',
        play: 'icon-bofang3',
        pause: 'icon-zanting6'
    },
    parentName = 'AudioController';
const AudioController = ({ music, displayMusicLyr, ctrlSong, lyricUp, clearLyrics }) => {
    const playBtnRef = useRef();
    const [others, setOthers] = useState(null);
    useEffect(() => {
        if (music.curSong && music.curSong.url) {
            console.log("audiocontroller init");
            let curAudio = music.curSong.audio,
                playBtn = playBtnRef.current;
            configPlayBtnOnce(curAudio, playBtn, playBtnClassNames, ctrlSong, parentName);
            // playBtn.className = `${playBtnClassNames.prefix} ${music.isPlaying ? playBtnClassNames.pause : playBtnClassNames.play}`;
            let others = {
                ctrlSong, playBtn: playBtnRef.current, lrc: music.curSong.lrc, lyricUp, displayLyrics: displayMusicLyr, curMusicTime
            }
            setOthers(others);
            clearLyrics();
        }
        return () => {
            console.log("Audio Controller destroyed!");
        }
    }, [music.curSong.url]);
    return (
        <div className="audio-controller">
            <ProgressBar type={1} others={others} />
            <div className="control-area">
                <span className="iconfont icon-danquxunhuan"></span>
                <span className="iconfont icon-047caozuo_shangyishou"></span>
                <span ref={playBtnRef} className="iconfont icon-play"></span>
                <span className="iconfont icon-048caozuo_xiayishou"></span>
                <span className="iconfont icon-liebiao"></span>
            </div>
        </div>
    )
}

export default connect(mapStateToProps, mapDispatchToProps)(AudioController);